package com.springboot.application.configs;

import cn.hutool.core.io.FileUtil;
import com.springboot.application.plugins.SqlPrintPlugin;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.SpringBootVFS;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.io.File;

@Configuration
@MapperScan("com.springboot.application.dao")
public class MyBatisConfig {

    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setVfs(SpringBootVFS.class);
        // 添加插件
        sqlSessionFactoryBean.setPlugins(new SqlPrintPlugin[]{new SqlPrintPlugin()});
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();


        // 获取相对路径下的 mapper.xml 文件是否存在
        File file = FileUtil.file("mapper");

        // 尝试获取 mapper.xml 文件
        if (file.exists()) {
            Resource[] mapperXmlResources = resolver.getResources("classpath:/mapper/*.xml");
            sqlSessionFactoryBean.setMapperLocations(mapperXmlResources);
        }
        return sqlSessionFactoryBean.getObject();
    }

    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}